package com.lzc.jobrecomendbackend.service.salary.impl;

import com.lzc.jobrecomendbackend.model.Job;
import com.lzc.jobrecomendbackend.model.salary.CityCompareVO;
import com.lzc.jobrecomendbackend.model.salary.SalaryDistributionVO;
import com.lzc.jobrecomendbackend.repository.JobRepository;
import com.lzc.jobrecomendbackend.service.salary.SalaryService;
import com.lzc.jobrecomendbackend.utils.SalaryParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SalaryServiceImpl implements SalaryService {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<SalaryDistributionVO> getSalaryDistribution(String city, String education, String experience) {
        // 构建查询条件
        Query query = new Query();
        if (city != null && !city.isEmpty()) {
            query.addCriteria(Criteria.where("工作城市").is(city));
        }
        if (education != null && !education.isEmpty()) {
            query.addCriteria(Criteria.where("学历要求").is(education));
        }
        if (experience != null && !experience.isEmpty()) {
            query.addCriteria(Criteria.where("经验要求").is(experience));
        }

        // 查询符合条件的职位
        List<Job> jobs = mongoTemplate.find(query, Job.class);
        
        // 定义薪资区间
        String[] ranges = {"10k以下", "10k-20k", "20k-30k", "30k-50k", "50k以上"};
        Map<String, Integer> rangeCounts = new HashMap<>();
        for (String range : ranges) {
            rangeCounts.put(range, 0);
        }
        
        // 统计各区间职位数
        for (Job job : jobs) {
            Double[] salaryRange = SalaryParser.parseSalary(job.get薪资待遇());
            if (salaryRange != null && salaryRange.length == 2) {
                double avgSalary = (salaryRange[0] + salaryRange[1]) / 2;
                String range = getSalaryRangeCategory(avgSalary);
                rangeCounts.put(range, rangeCounts.get(range) + 1);
            }
        }
        
        // 转换为返回结果
        return rangeCounts.entrySet().stream()
                .map(entry -> new SalaryDistributionVO(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
    }

    @Override
    public List<CityCompareVO> getCityCompare(String education, String experience, String positionKeyword) {
        List<String> cities = Arrays.asList("北京", "上海", "广州");
        List<CityCompareVO> result = new ArrayList<>();
        
        for (String city : cities) {
            // 构建查询条件
            Query query = new Query();
            query.addCriteria(Criteria.where("工作城市").is(city));
            
            if (education != null && !education.isEmpty()) {
                query.addCriteria(Criteria.where("学历要求").is(education));
            }
            if (experience != null && !experience.isEmpty()) {
                query.addCriteria(Criteria.where("经验要求").is(experience));
            }
            if (positionKeyword != null && !positionKeyword.isEmpty()) {
                query.addCriteria(Criteria.where("职位名字").regex(positionKeyword));
            }
            
            // 查询符合条件的职位
            List<Job> jobs = mongoTemplate.find(query, Job.class);
            
            // 解析薪资数据
            List<Double> minSalaries = new ArrayList<>();
            List<Double> maxSalaries = new ArrayList<>();
            List<Double> avgSalaries = new ArrayList<>();
            
            for (Job job : jobs) {
                Double[] salaryRange = SalaryParser.parseSalary(job.get薪资待遇());
                if (salaryRange != null && salaryRange.length == 2) {
                    minSalaries.add(salaryRange[0]);
                    maxSalaries.add(salaryRange[1]);
                    avgSalaries.add((salaryRange[0] + salaryRange[1]) / 2);
                }
            }
            
            // 如果没有有效薪资数据，添加默认值
            if (avgSalaries.isEmpty()) {
                result.add(new CityCompareVO(
                    city,
                    "0k",
                    new CityCompareVO.SalaryRange("0k", "0k")
                ));
                continue;
            }
            
            // 计算平均值
            double minSalary = minSalaries.stream().mapToDouble(Double::doubleValue).min().orElse(0);
            double maxSalary = maxSalaries.stream().mapToDouble(Double::doubleValue).max().orElse(0);
            double avgSalary = avgSalaries.stream().mapToDouble(Double::doubleValue).average().orElse(0);
            
            // 添加到结果
            result.add(new CityCompareVO(
                city,
                String.format("%.1fk", avgSalary),
                new CityCompareVO.SalaryRange(
                    String.format("%.1fk", minSalary),
                    String.format("%.1fk", maxSalary)
                )
            ));
        }
        
        return result;
    }
    
    /**
     * 获取薪资所在区间类别
     */
    private String getSalaryRangeCategory(double salary) {
        if (salary < 10) return "10k以下";
        else if (salary < 20) return "10k-20k";
        else if (salary < 30) return "20k-30k";
        else if (salary < 50) return "30k-50k";
        else return "50k以上";
    }
} 